package com.yj.suncity.activity.shouye;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.R;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.ThreadUtils;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.async.ThreadUtils.OnResultListener;
import com.yj.suncity.bean.AdvDetailBean;
import com.yj.suncity.bean.HuodongDetailBean;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.LoginActivity;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class HuodongDetailActivity extends Activity implements OnClickListener {

	private static final int PAGER = 101;
	private Context context;
	private String huodongId;
	private ViewPager pager;
	private LinearLayout lay_view_select;
	private int mWidth;
	private ViewPagerScroll pagerScroll;
	private String userId = "";
	private Button mBtn_duihuan_digou;
	private List<Object> listPaths = new ArrayList<Object>();
	private TextView mTxt_activity_theme, mTxt_activity_time,
			mTxt_activity_address;
	private String mContent = "";
	private boolean isCollect;
	private ImageView mImag_collect_normal, mImag_collect_press;
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();
	private boolean isLogin;
	
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	
	private TextView mTxt_shop_name, mTxt_shop_jianjie;
	private TextView mTxt_contact_name, mTxt_contact_phone,
			mTxt_contact_address;// 联系
	private ImageView mImg_logo;

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case PAGER:
				onResume();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_huodong_detail);
		context = this;
		mWidth = getResources().getDisplayMetrics().widthPixels;
		huodongId = getIntent().getStringExtra("huodongid");
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		findView();
		initData();
	}

	private void findView() {
		mImag_collect_normal = (ImageView) findViewById(R.id.img_collet_normal);
		mImag_collect_press = (ImageView) findViewById(R.id.img_collet_press);
		findViewById(R.id.btnHeadBack).setOnClickListener(this);

		mTxt_shop_name = (TextView) findViewById(R.id.txt_shop_name);
		mTxt_shop_jianjie = (TextView) findViewById(R.id.txt_shop_jianjie);
		mImg_logo = (ImageView) findViewById(R.id.img_logo);
		mTxt_contact_name = (TextView) findViewById(R.id.txt_contact_name);
		mTxt_contact_phone = (TextView) findViewById(R.id.txt_contact_phone);
		mTxt_contact_address = (TextView) findViewById(R.id.txt_contact_address);
		
		mBtn_duihuan_digou = (Button) findViewById(R.id.btn_ok);
		mBtn_duihuan_digou.setOnClickListener(this);
		mBtn_duihuan_digou.setText("我要参与");

		lay_view_select = (LinearLayout) findViewById(R.id.lay_view_select);
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.lay_view_page);
		layout.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
				(int) (mWidth / 2)));
		pager = (ViewPager) findViewById(R.id.view_pager);
		// ==========================================================================================

		mTxt_activity_theme = (TextView) findViewById(R.id.txt_activity_theme);
		mTxt_activity_time = (TextView) findViewById(R.id.txt_activity_time);
		mTxt_activity_address = (TextView) findViewById(R.id.txt_activity_address);
	}

	private void initData() {
		String path = URLCon.活动 + "?action=getactivity&id=" + huodongId
				+ "&userid=" + userId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在加载......", new ResultCallBack() {

					@Override
					public void JSONResult(JSONObject jsonObject) {
						HuodongDetailBean productBean = new HuodongDetailBean(
								jsonObject);
						initShopInfo(productBean.getRelease_userid());
						if (productBean.getImg_list().contains(",")) {
							String[] string = productBean.getImg_list().split(
									",");
							for (String string2 : string) {
								listPaths.add(URLCon.HOST + string2);
							}
						} else {
							listPaths.add(URLCon.HOST
									+ productBean.getImg_list());
						}
						pagerScroll = new ViewPagerScroll(context, pager,
								lay_view_select, listPaths);

						Message message = new Message();
						message.what = PAGER;
						handler.sendMessage(message);

						mTxt_activity_theme.setText(productBean
								.getActivity_theme());
						mTxt_activity_time.setText(Utils
								.DateFormatDate(productBean
										.getActivity_enddatetime()));

						mContent = productBean.getActivity_content();
						mTxt_activity_address.setText(productBean
								.getActivity_address());
					}
				});
		asyncTaskUtil.execute(path);
	}
	
	private void initShopInfo(String shopUserId) {
		String path = URLCon.广告 + "?action=seeadvdetail&id=" + shopUserId;
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				final AdvDetailBean advDetailBean = new AdvDetailBean(json);
				imageLoader.displayImage(
						URLCon.HOST + advDetailBean.getEnt_logo(), mImg_logo,
						options);

				mTxt_shop_name.setText(advDetailBean.getEntname());
				mTxt_shop_jianjie.setText(advDetailBean.getEnt_jianjie());

				mTxt_contact_name.setText(advDetailBean.getEnt_contact());
				mTxt_contact_phone.setText(advDetailBean.getEnt_contact_tel());
				mTxt_contact_address.setText(advDetailBean.getEnt_address());
				mTxt_contact_phone.setOnClickListener(new OnClickListener() {// 拨打电话
							@Override
							public void onClick(View v) {
								DialogUtils dialogUtils = DialogUtils
										.getInstance();
								dialogUtils.CallDialog(context,
										advDetailBean.getEnt_contact_tel());
							}
						});
			}
		});

	}

	@Override
	protected void onResume() {
		isLogin = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.ISLOGIN, false);
		if (isLogin) {
			userId = preferencesUtil.getString(context, ShareCon.USERFILE,
					ShareCon.USERID, "");
			getCollectStatus();
		}
		if (pagerScroll != null) {
			pagerScroll.startTimer();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (pagerScroll != null) {
			pagerScroll.stopTimer();
		}
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;
		case R.id.lay_rela_huodong_detail:
			Intent intent = new Intent(this, ProductDetailWebActivity.class);
			intent.putExtra("content", mContent);
			startActivity(intent);
			break;
		case R.id.lay_rela_collect:// 添加/移除收藏
			if (!isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			if (isCollect) {
				removeCollect();
			} else {
				addCollect();
			}
			break;
		case R.id.btn_ok:

			break;
		}
	}

	private void addCollect() {
		String path = URLCon.收藏 + "?action=addcollection&userid=" + userId
				+ "&id=" + huodongId + "&type=7";
		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "添加收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = true;
							mImag_collect_normal.setVisibility(View.GONE);
							mImag_collect_press.setVisibility(View.VISIBLE);
							ToastUtil.ShowToast(context, "收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void getCollectStatus() {
		String path = URLCon.收藏 + "?action=getcollectionstate&userid=" + userId
				+ "&id=" + huodongId + "&type=7";

		Log.d("", "获取收藏：" + path);
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				if (json.optString("success").equals("1")) {
					if (json.optString("state").equals("1")) {
						isCollect = true;
						mImag_collect_normal.setVisibility(View.GONE);
						mImag_collect_press.setVisibility(View.VISIBLE);
					} else {
						isCollect = false;
						mImag_collect_normal.setVisibility(View.VISIBLE);
						mImag_collect_press.setVisibility(View.GONE);
					}
				}
			}
		});
	}

	private void removeCollect() {
		String path = URLCon.收藏 + "?action=delcollection&userid=" + userId
				+ "&id=" + huodongId + "&type=7";

		Log.d("", "添加收藏：" + path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "删除收藏......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							isCollect = false;
							setResult(1);
							mImag_collect_normal.setVisibility(View.VISIBLE);
							mImag_collect_press.setVisibility(View.GONE);
							ToastUtil.ShowToast(context, "删除收藏成功！");
						} else {
							ToastUtil.ShowToast(context,
									"" + jsonObject.optString("msg"));
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

}
